package com.lottery.material.controller.portal.article;

import com.lottery.material.controller.base.BaseController;
import com.lottery.material.enumeration.ResultEnum;
import com.lottery.material.jedis.JedisClient;
import com.lottery.material.pojo.promotion.PromotionRuleConfig;
import com.lottery.material.resolver.CustomException;
import com.lottery.material.service.portal.article.ArticleActiveInfoService;
import com.lottery.material.service.portal.article.ArticleInfoService;
import com.lottery.material.service.portal.config.SystemParameterConfigService;
import com.lottery.material.service.portal.promotion.PromotionRuleConfigService;
import com.lottery.material.service.portal.user.PortalUserInfoService;
import com.lottery.material.util.*;
import com.lottery.material.vo.portal.article.ArticleInfoListVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description:    文章列表接口Controller
 * Author:         sunny
 * CreateDate:     2019-04-19 20:40
 */
@RequestMapping("/portal/article")
@Slf4j
@Controller
public class ArticleInfoListController extends BaseController {

    @Autowired
    @Qualifier("jedisClientCluster")
    private JedisClient jedisClient;

    @Autowired
    private SystemParameterConfigService systemParameterConfigService;
    @Autowired
    private ArticleActiveInfoService articleActiveInfoService;
    @Autowired
    private ArticleInfoService articleInfoService;
    @Autowired
    private PromotionRuleConfigService promotionRuleConfigService;
    @Autowired
    private PortalUserInfoService portalUserInfoService;

    /**
     * description: 获取首页、精彩和广场文章分页列表
     * author sunny
     * createDate 2019-04-19 下午 8:46
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getArticlePageList", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult getArticlePageList(HttpServletRequest request) {
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断
        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String menuCode = reqParamMap.get("menuCode");
        if (StringUtils.isBlank(menuCode)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "menuCode");
        }

        String page = reqParamMap.get("page");
        String refreshTime = reqParamMap.get("refreshTime");
        if (StringUtils.isBlank(page)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "page");
        } else {
            if ("1".equals(page)) {
                refreshTime = CalendarUtil.getNowDate();
            } else {
                if (StringUtils.isBlank(refreshTime)) {
                    return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "refreshTime");
                }
            }
        }

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if (null != responseResult) {
            return responseResult;
        }

        try {
            reqParamMap.put("refreshTime", refreshTime);
            if ("MQS00001".equals(menuCode)) { //热帖
                return returnHotList(reqParamMap);
            } else if ("MQS00002".equals(menuCode)) { //关注
                //非空判断及用户登录是否过期验证
                ParameterUtil.checkLogin(reqParamMap, jedisClient, portalUserInfoService);
                return returnAttentionList(reqParamMap);
            } else if ("MJC00001".equals(menuCode)) { //精彩
                return returnWonderfulList(reqParamMap);
            } else if ("MGC00001".equals(menuCode)) { //广场
                return returnPlazaList(reqParamMap);
            } else { //足球或篮球或自定义
                return returnPublicList(reqParamMap);
            }
        } catch (Exception e) {
            log.error("【获取首页、精彩和广场文章分页列表出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GET_ARTICLE_PAGE_LIST_EXCEPTION);
        }
    }

    /**
     * description: 获取当前比赛下的所有文章分页列表
     * author sunny
     * createDate 2019-04-23 上午 10:43
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getCompetitionArticlePageList", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult getCompetitionArticlePageList(HttpServletRequest request) {
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断
        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String matchId = reqParamMap.get("matchId");
        if (StringUtils.isBlank(matchId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "matchId");
        }

        String page = reqParamMap.get("page");
        String refreshTime = reqParamMap.get("refreshTime");
        if (StringUtils.isBlank(page)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "page");
        } else {
            if ("1".equals(page)) {
                refreshTime = CalendarUtil.getNowDate();
            } else {
                if (StringUtils.isBlank(refreshTime)) {
                    return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "refreshTime");
                }
            }
        }

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if (null != responseResult) {
            return responseResult;
        }

        try {
            Map<String, Object> competitionMap = new HashMap<String, Object>();
            competitionMap.put("matchId", matchId);
            competitionMap.put("refreshTime", refreshTime);
            competitionMap.put("pageIndex", Const.PORTAL_PAGE * (Integer.valueOf(page) - 1));
            competitionMap.put("pageCount", Const.PORTAL_PAGE);
            List<ArticleInfoListVo> competitionArticleList = articleInfoService.findCompetitionArticle(competitionMap);

            //封装响应数据
            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("refreshTime", reqParamMap.get("refreshTime"));
            responseMap.put("articleList", competitionArticleList);
            return ResponseResult.buildResult(ResultEnum.SUCCESS, responseMap);
        } catch (Exception e) {
            log.error("【获取当前比赛下的所有文章分页列表出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GET_COMPETITION_ARTICLE_PAGE_LIST_EXCEPTION);
        }
    }

    /**
     * description: 获取当前圈子下的所有文章分页列表
     * author sunny
     * createDate 2019-04-23 下午 2:52
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getCircleArticlePageList", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult getCircleArticlePageList(HttpServletRequest request) {
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断
        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String circleId = reqParamMap.get("circleId");
        if (StringUtils.isBlank(circleId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "circleId");
        }

        String sortType = reqParamMap.get("sortType");
        if (StringUtils.isBlank(sortType)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "sortType");
        }else if (!"1".equals(sortType) && !"2".equals(sortType)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_ERROR, "sortType");
        }

        String page = reqParamMap.get("page");
        String refreshTime = reqParamMap.get("refreshTime");
        if (StringUtils.isBlank(page)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "page");
        } else {
            if ("1".equals(page)) {
                refreshTime = CalendarUtil.getNowDate();
            } else {
                if (StringUtils.isBlank(refreshTime)) {
                    return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "refreshTime");
                }
            }
        }

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if (null != responseResult) {
            return responseResult;
        }

        try {
            Map<String, Object> circleMap = new HashMap<String, Object>();
            circleMap.put("circleId", circleId);
            circleMap.put("sortType", sortType);
            circleMap.put("refreshTime", refreshTime);
            circleMap.put("pageIndex", Const.PORTAL_PAGE * (Integer.valueOf(page) - 1));
            circleMap.put("pageCount", Const.PORTAL_PAGE);
            List<ArticleInfoListVo> circleArticleList = articleInfoService.findCircleArticle(circleMap);

            //封装响应数据
            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("refreshTime", reqParamMap.get("refreshTime"));
            responseMap.put("articleList", circleArticleList);
            return ResponseResult.buildResult(ResultEnum.SUCCESS, responseMap);
        } catch (Exception e) {
            log.error("【获取当前圈子下的所有文章分页列表出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GET_CIRCLE_ARTICLE_PAGE_LIST_EXCEPTION);
        }
    }

    /**
     * description: 返回热帖列表数据
     * author sunny
     * createDate 2019-04-22 下午 5:38
     *
     * @param reqParamMap
     * @return
     */
    private ResponseResult returnHotList(Map<String, String> reqParamMap) {
        Integer page = Integer.valueOf(reqParamMap.get("page"));
        //获取圈子内文章推广规则配置信息
        PromotionRuleConfig promotionRuleConfig = promotionRuleConfigService.findByPromotionType(1);
        int promotionMaximum = Integer.valueOf(promotionRuleConfig.getPromotionLimit());
        int promotionPageCount = Const.PORTAL_PAGE / 2; //推广文章每页显示的数量
        int promotionPage = (int) Math.ceil((double) promotionMaximum / (double) promotionPageCount); //推广文章需要显示几页

        List<ArticleInfoListVo> promotionArticleList = new ArrayList<ArticleInfoListVo>();
        if (page <= promotionPage) { //需要查询推广文章
            Map<String, Object> promotionMap = new HashMap<String, Object>();
            promotionMap.put("refreshTime", reqParamMap.get("refreshTime"));
            promotionMap.put("pageIndex", promotionPageCount * (page - 1));
            promotionMap.put("pageCount", promotionPageCount);
            promotionArticleList = articleActiveInfoService.findPromotionArticle(promotionMap);
        }

        int hotPageCount = Const.PORTAL_PAGE - promotionArticleList.size(); //排除推广文章，计算热帖文章每页显示的数量
        Map<String, Object> promotionMap = new HashMap<String, Object>();
        promotionMap.put("refreshTime", reqParamMap.get("refreshTime"));
        promotionMap.put("pageIndex", hotPageCount * (page - 1));
        promotionMap.put("pageCount", hotPageCount);
        List<ArticleInfoListVo> hotArticleList = articleActiveInfoService.findHotArticle(promotionMap);

        //封装响应数据
        Map<String, Object> responseMap = new HashMap<String, Object>();
        responseMap.put("refreshTime", reqParamMap.get("refreshTime"));
        responseMap.put("articleList", hotDataMerge(promotionArticleList, hotArticleList));
        return ResponseResult.buildResult(ResultEnum.SUCCESS, responseMap);
    }

    /**
     * description: 返回关注列表数据
     * author sunny
     * createDate 2019-04-22 下午 5:42
     *
     * @param reqParamMap
     * @return
     */
    private ResponseResult returnAttentionList(Map<String, String> reqParamMap) {
        Integer page = Integer.valueOf(reqParamMap.get("page"));
        Map<String, Object> attentionMap = new HashMap<String, Object>();
        attentionMap.put("refreshTime", reqParamMap.get("refreshTime"));
        attentionMap.put("pageIndex", Const.PORTAL_PAGE * (page - 1));
        attentionMap.put("pageCount", Const.PORTAL_PAGE);
        List<ArticleInfoListVo> attentionArticleList = articleActiveInfoService.findAttentionArticle(attentionMap);

        //封装响应数据
        Map<String, Object> responseMap = new HashMap<String, Object>();
        responseMap.put("refreshTime", reqParamMap.get("refreshTime"));
        responseMap.put("attentionArticleList", attentionArticleList);
        return ResponseResult.buildResult(ResultEnum.SUCCESS, responseMap);
    }

    /**
     * description: 返回足球或篮球或自定义列表数据
     * author sunny
     * createDate 2019-04-22 下午 8:07
     *
     * @param reqParamMap
     * @return
     */
    private ResponseResult returnPublicList(Map<String, String> reqParamMap) {
        Integer page = Integer.valueOf(reqParamMap.get("page"));
        Map<String, Object> publicMap = new HashMap<String, Object>();
        publicMap.put("menuCode", reqParamMap.get("menuCode"));
        publicMap.put("refreshTime", reqParamMap.get("refreshTime"));
        publicMap.put("pageIndex", Const.PORTAL_PAGE * (page - 1));
        publicMap.put("pageCount", Const.PORTAL_PAGE);
        List<ArticleInfoListVo> publicArticleList = articleActiveInfoService.findPublicArticle(publicMap);

        //封装响应数据
        Map<String, Object> responseMap = new HashMap<String, Object>();
        responseMap.put("refreshTime", reqParamMap.get("refreshTime"));
        responseMap.put("articleList", publicArticleList);
        return ResponseResult.buildResult(ResultEnum.SUCCESS, responseMap);
    }

    /**
     * description: 返回广场列表数据
     * author sunny
     * createDate 2019-04-22 下午 8:14
     *
     * @param reqParamMap
     * @return
     */
    private ResponseResult returnPlazaList(Map<String, String> reqParamMap) {
        Integer page = Integer.valueOf(reqParamMap.get("page"));
        Map<String, Object> plazaMap = new HashMap<String, Object>();
        plazaMap.put("refreshTime", reqParamMap.get("refreshTime"));
        plazaMap.put("pageIndex", Const.PORTAL_PAGE * (page - 1));
        plazaMap.put("pageCount", Const.PORTAL_PAGE);
        List<ArticleInfoListVo> plazaArticleList = articleActiveInfoService.findPlazaArticle(plazaMap);

        //封装响应数据
        Map<String, Object> responseMap = new HashMap<String, Object>();
        responseMap.put("refreshTime", reqParamMap.get("refreshTime"));
        responseMap.put("articleList", plazaArticleList);
        return ResponseResult.buildResult(ResultEnum.SUCCESS, responseMap);
    }

    /**
     * description: 返回精彩列表数据
     * author sunny
     * createDate 2019-04-23 上午 9:22
     *
     * @param reqParamMap
     * @return
     */
    private ResponseResult returnWonderfulList(Map<String, String> reqParamMap) {
        Integer page = Integer.valueOf(reqParamMap.get("page"));
        Map<String, Object> wonderfulMap = new HashMap<String, Object>();
        wonderfulMap.put("refreshTime", reqParamMap.get("refreshTime"));
        wonderfulMap.put("pageIndex", Const.PORTAL_PAGE * (page - 1));
        wonderfulMap.put("pageCount", Const.PORTAL_PAGE);
        List<ArticleInfoListVo> wonderfulArticleList = articleActiveInfoService.findWonderfulArticle(wonderfulMap);

        //封装响应数据
        Map<String, Object> responseMap = new HashMap<String, Object>();
        responseMap.put("refreshTime", reqParamMap.get("refreshTime"));
        responseMap.put("articleList", wonderfulArticleList);
        return ResponseResult.buildResult(ResultEnum.SUCCESS, responseMap);
    }

    /**
     * description: 热帖展示数据合并
     * author sunny
     * createDate 2019-04-22 下午 4:30
     *
     * @param promotionArticleList
     * @param hotArticleList
     * @return
     */
    private List<ArticleInfoListVo> hotDataMerge(List<ArticleInfoListVo> promotionArticleList, List<ArticleInfoListVo> hotArticleList) {
        List<ArticleInfoListVo> articleList = new ArrayList<ArticleInfoListVo>();

        int promotionIndex = 0;
        int promotionCount = 0;
        int hotIndex = 0;
        int hotCount = 0;

        if (null != promotionArticleList && promotionArticleList.size() > 0) {
            promotionCount = promotionArticleList.size();
        }

        if (null != hotArticleList && hotArticleList.size() > 0) {
            hotCount = hotArticleList.size();
        }

        for (int i = 0; i < 20; i++) {
            if (i % 2 == 0) {
                if (hotIndex < hotCount) {
                    articleList.add(hotArticleList.get(hotIndex));
                    hotIndex++;
                } else if (promotionIndex < promotionCount) {
                    articleList.add(promotionArticleList.get(promotionIndex));
                    promotionIndex++;
                }
            } else {
                if (promotionIndex < promotionCount) {
                    articleList.add(promotionArticleList.get(promotionIndex));
                    promotionIndex++;
                } else if (hotIndex < hotCount) {
                    articleList.add(hotArticleList.get(hotIndex));
                    hotIndex++;
                }
            }
        }
        return articleList;
    }
}
